import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;

public class TrackClient extends Thread implements Client {

	private Socket trackSocket;
	private ArrayList<String> history;
	private BufferedReader trackReader;
	private PrintWriter trackWriter;

	public TrackClient() {
		history = new ArrayList<String>();
	}

	public boolean connect(String ip, int port, String marker) {
		try {
			trackSocket = new Socket(ip, port);
			trackReader = new BufferedReader(new InputStreamReader(trackSocket.getInputStream()));
			trackWriter = new PrintWriter(new OutputStreamWriter(trackSocket.getOutputStream()));
		} catch (Exception e) {
			return false;
		}
		
		write("CM_GETSYSTEM");
		if(!read().split(" ")[0].equals("ANS_TRUE")){
			System.out.println("CM_GETSYSTEM failed");
			return false;
		}
		
		write(marker);
//		write("PolarisActive_1");
//		write("sync");
//		System.out.println(read());
		if(!read().equals("ANS_TRUE")){
			System.out.println("Marker failed");
			return false;
		}
		
		write("FORMAT_MATRIXROWWISE");
		if(!read().equals("ANS_TRUE")){
			System.out.println("FORMAT failed");
			return false;
		}

		return true;
	}

	public void write(String command) {
		trackWriter.println(command);
		trackWriter.flush();
		history.add("W: " + command);
	}

	public String read() {
		String line = "failed";
		try {
			line = trackReader.readLine();
		} catch (IOException e) {
			e.printStackTrace();
		}
//		System.out.println(line);
		history.add("R: " + line);
		return line;
	}

	public void showHistory() {
		for (int i = 0; i < history.size(); i++) {
			System.out.println(history.get(i));
		}
	}

}
